package com.zhuhjay.app.web.controller.system;

import com.zhuhjay.common.base.controller.BaseController;
import com.zhuhjay.common.redis.util.RedisUtils;
import com.zhuhjay.common.web.model.vo.PageInfoVo;
import com.zhuhjay.service.system.model.dto.BlackDto;
import com.zhuhjay.service.system.model.entity.SystemBlack;
import com.zhuhjay.service.system.service.SystemBlackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import static com.zhuhjay.common.base.constant.CacheConstant.BLACK_KEY;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ZhuHJay
 * @since 2023-06-17
 */
@Api(tags = "黑名单")
@Validated
@RestController
@RequestMapping("/black")
public class SystemBlackController extends BaseController {

    @Resource
    private SystemBlackService blackService;

    @ApiOperation("获取黑名单列表")
    @GetMapping("page/{pageNum}/{pageSize}")
    @PreAuthorize("@perm.hasPerm('system:manager:black:list')")
    public PageInfoVo<SystemBlack> page(
            @PathVariable @Range(min = 1, max = Integer.MAX_VALUE) Integer pageNum,
            @PathVariable @Range(min = 5, max = 30) Integer pageSize) {
        return blackService.blackPage(pageNum, pageSize);
    }

    @ApiOperation("添加黑名单")
    @PostMapping("add")
    @PreAuthorize("@perm.hasPerm('system:manager:black:add')")
    public void add(@RequestBody @Valid BlackDto blackDto) {
        blackService.add(blackDto);
    }

    @ApiOperation("移除黑名单")
    @DeleteMapping("remove/{id}")
    @PreAuthorize("@perm.hasPerm('system:manager:black:remove')")
    public void remove(@PathVariable Long id) {
        SystemBlack black = blackService.getById(id);
        if (black == null) {
            return;
        }
        blackService.removeById(id);
        RedisUtils.removeValue4Set(BLACK_KEY, black.getTarget());
    }

}
